/**
 * 事件监听
 */
chrome.runtime.onMessage.addListener((e, _, sendResponse) => {
  switch (e.action) {
    case 'fromSW2Popup-sendCoverage': {
      const coverageUl = document.getElementById('window_coverage')
      const li = document.createElement('li')
      li.innerHTML = `
        <div>url: ${e.message.location.href}</div>
        <div>coverage: ${e.message.data ? JSON.stringify(e.message.data) : ''}</div>
      `
      coverageUl.appendChild(li)
      break
    }
    default:
      break
  }
  sendResponse()
  return false
})

const get_window_but = document.getElementById('get_window_but')

/**
 * but 按钮事件
 */
get_window_but.onclick = async () => {
  const tabId = await getCurrentTabId()
  // 从 popup 发送消息到  SW
  tabId && chrome.runtime.sendMessage({
    action: 'fromPopup2SW-getWindowData',
    message: {
      tabId
    }
  })
}

/**
 * 获取当前活动页面的 id
 * @returns {string} tabId
 */
const getCurrentTabId = async () => {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  return tabs && tabs.length > 0 ? tabs[0].id : ''
}